package admin_api

import (
	"fmt"
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"shop/admin/admin_service"
	"shop/utils/result"
	"shop/utils/sessionutil"
	"shop/utils/tcentcloudutil"
)

func GetUserInfo(ctx *gin.Context) {
	user := sessionutil.GetSysUserInfo(sessionutil.GetSysUserIdFromCtx(ctx))
	result.RenderResult(ctx, result.Ok(user))
}

func UpdatePassword(ctx *gin.Context) {
	params := &admin_service.UpdatePasswordParams{}
	err := ctx.ShouldBindJSON(params)
	if err != nil {
		result.RenderResult(ctx, result.Fail("参数格式错误"))
		return
	}
	if len(params.OldPassword) < 6 || len(params.OldPassword) > 20 || len(params.NewPassword) < 6 || len(params.NewPassword) > 20 {
		result.RenderResult(ctx, result.Fail("密码长度必须是6-20位之间"))
		return
	}

	result.RenderResult(ctx, admin_service.UpdatePassword(sessionutil.GetSysUserIdFromCtx(ctx), params))
}

func UploadUserAvatar(ctx *gin.Context) {
	formFile, err := ctx.FormFile("file")
	if err != nil {
		seelog.Errorf("表单文件解析失败，err: %v, formFile: %v", err, formFile)
		result.RenderResult(ctx, result.Fail("文件解析失败"))
		return
	}

	file, err := formFile.Open()
	if err != nil {
		seelog.Errorf("文件打开失败，err: %v, formFile: %v", err, formFile)
		result.RenderResult(ctx, result.Fail("服务器异常：文件打开失败"))
		return
	}

	userId := sessionutil.GetSysUserIdFromCtx(ctx)
	objKey := fmt.Sprintf("sysUserAvatar/%d/%s", userId, formFile.Filename)
	url, err := tcentcloudutil.PutObject(objKey, file)
	if err != nil {
		result.RenderResult(ctx, result.Fail("图片上传失败: "+err.Error()))
		return
	}
	result.RenderResult(ctx, admin_service.UpdateUserAvatar(userId, url))
}
